'use strict';

angular.module('wb-tea.services', []).factory('MainPageSvc', function ($http) {
	// get data from server

	function getData(callback) {
		// Simple GET request example:
		$http({
			method: 'GET',
			url: 'http://www.fair369.com/api_ad_index/getAdIndex'
		}).then(function successCallback(response) {
			// this callback will be called asynchronously
			// when the response is available
			callback.successCallback(response);
		}, function errorCallback(response) {
			// called asynchronously if an error occurs
			// or server returns response with an error status.
			callback.errorCallback(response);
		});
	}

	return {
		fetchData: function fetchData(callback) {
			return getData(callback);
		}
	};
}).factory('UrlUtils', function () {
	return {
		// BASE_URL: 'http://wanchabang.52kaike.com/api/'
		// BASE_URL: 'http://www.wcbtea.com/api/'
		BASE_URL: 'http://120.24.250.20:8080/api/',
		NEW_BASE_URL: 'http://120.24.250.20/index.php/api/',
	};
}).factory('KuaiDiService', ['$ionicLoading', function ($ionicLoading) {

	 //同步加载动画
    $ionicLoading.show({
        template: 'Loading...'
    });

	var getInfo = function(orderID, kuaidiType, callback) {
		$.ajax({
			type: "GET",
			url: "http://www.kuaidi100.com/applyurl",
			data: {
				key: 'f07da2f093186d7f',
				com: kuaidiType,
				nu: orderID,
			},
			success: function(data) {
				console.log("检测请求返回：");
           		console.log(data);

           		setTimeout(function(){
	   				$ionicLoading.hide();
	   			},500);

	   			callback.success && callback.success(data);
			},
			error: function() {
	            setTimeout(function(){
	   				$ionicLoading.hide();
	   			},500);

	            callback.failed && callback.failed("操作失败, 请重试。");

	            if (callback.failed == null) alert("操作失败, 请重试。");
          	}
		})
	};

	return {
		getKuaiDiUrl: getInfo,
	}
}]).factory('HttpService', ['$http', 'UrlUtils', '$ionicLoading', function ($http, UrlUtils, $ionicLoading,$rootScope) {

	var URL = UrlUtils.BASE_URL;

	var post = function post(_ref) {
		var name = _ref.name;
		var params = _ref.params;
		var callback = _ref.callback;

		var url = URL.concat(name);
        console.log('post url = ' + url);
        console.log('post params = ' + JSON.stringify(params));

        //同步加载动画
        $ionicLoading.show({
            template: 'Loading...'
        });

        $.ajax({
          type: "POST",
          url: url,
          data: params,
          success: function(response) {
           console.log("检测请求返回：");
           console.log(JSON.stringify(response));
           			setTimeout(function(){
           				 $ionicLoading.hide();
           			},500);

                      if (response.code == 200) {
                          if (response.data != null) {
                              callback.success && callback.success(response.data);
                          } else {
                              callback.success && callback.success(response);
                          }
                      } else {
                          callback.failed && callback.failed(response.msg);
                          // if (callback.failed == null) $rootScope.alert_err(response.msg);
													if (callback.failed == null) alert(response.msg);
                      }
          },
          error: function() {
            setTimeout(function(){
   				$ionicLoading.hide();
   			},500);
            callback.failed && callback.failed("操作失败, 请重试。");
            if (callback.failed == null) alert("操作失败, 请重试。");
          }
        });

//		$http.post(url, params, {
//		    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
//		    params: params,
//		    data: params,
//		}).success(function(response) {
//		    console.log("检测请求返回：");
//            console.log(response);
//            if (response.code == 200) {
//                if (response.data != null) {
//                    callback.success && callback.success(response.data);
//                } else {
//                    callback.success && callback.success(response);
//                }
//            } else {
//                callback.failed && callback.failed(response.msg);
//                if (callback.failed == null) alert(response.msg);
//            }
//		});

//		var req = {
//			method: 'POST',
//			url: url,
//			headers: {
//				'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
//			},
//			transformRequest: function transformRequest(obj) {
//				var str = [];
//				for (var p in obj) {
//					str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
//				}
//
//				console.log('transformRequest = ' + str.join("&"))
//
//				return str.join("&");
//			},
//			data: params
//		};
//




//		$http(req).success(function (response) {
//			//响应成功
//			console.log("检测请求返回：");
//			console.log(response);
//			if (response.code == 200) {
//				if (response.data != null) {
//					callback.success && callback.success(response.data);
//				} else {
//					callback.success && callback.success(response);
//				}
//			} else {
//				callback.failed && callback.failed(response.msg);
//				if (callback.failed == null) alert(response.msg);
//			}
//		}).error(function (response) {
//			//处理响应失败
//			alert("连接服务失败！");
//		});
	};

	return post;
}]).factory('HttpServiceForNew', ['$http', 'UrlUtils', '$ionicLoading', function ($http, UrlUtils, $ionicLoading,$rootScope) {

	var URL = UrlUtils.NEW_BASE_URL;

	var post = function post(_ref) {
		var name = _ref.name;
		var params = _ref.params;
		var callback = _ref.callback;
		var type = _ref.type;

		var url = URL.concat(name);
        console.log('post url = ' + url);
        console.log('post params = ' + JSON.stringify(params));

        //同步加载动画
        $ionicLoading.show({
            template: 'Loading...'
        });

        $.ajax({
          type: type == null ? "POST" : type,
          url: url,
          data: params,
          success: function(response) {
           console.log("检测请求返回：");
           console.log(JSON.stringify(response));
           			setTimeout(function(){
           				 $ionicLoading.hide();
           			},500);

                      if (response.code == 200) {
                          if (response.data != null) {
                              callback.success && callback.success(response.data);
                          } else {
                              callback.success && callback.success(response);
                          }
                      } else {
                          callback.failed && callback.failed(response.msg);
                          if (callback.failed == null) $rootScope.alert_err(response.msg);
                      }
          },
          error: function() {
            setTimeout(function(){
   				$ionicLoading.hide();
   			},500);
            callback.failed && callback.failed("操作失败, 请重试。");
            if (callback.failed == null) alert("操作失败, 请重试。");
          }
        });

//		$http.post(url, params, {
//		    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
//		    params: params,
//		    data: params,
//		}).success(function(response) {
//		    console.log("检测请求返回：");
//            console.log(response);
//            if (response.code == 200) {
//                if (response.data != null) {
//                    callback.success && callback.success(response.data);
//                } else {
//                    callback.success && callback.success(response);
//                }
//            } else {
//                callback.failed && callback.failed(response.msg);
//                if (callback.failed == null) alert(response.msg);
//            }
//		});

//		var req = {
//			method: 'POST',
//			url: url,
//			headers: {
//				'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
//			},
//			transformRequest: function transformRequest(obj) {
//				var str = [];
//				for (var p in obj) {
//					str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
//				}
//
//				console.log('transformRequest = ' + str.join("&"))
//
//				return str.join("&");
//			},
//			data: params
//		};
//




//		$http(req).success(function (response) {
//			//响应成功
//			console.log("检测请求返回：");
//			console.log(response);
//			if (response.code == 200) {
//				if (response.data != null) {
//					callback.success && callback.success(response.data);
//				} else {
//					callback.success && callback.success(response);
//				}
//			} else {
//				callback.failed && callback.failed(response.msg);
//				if (callback.failed == null) alert(response.msg);
//			}
//		}).error(function (response) {
//			//处理响应失败
//			alert("连接服务失败！");
//		});
	};

	return post;
}]).factory('HttpService2', ['$http', 'UrlUtils', '$ionicLoading', function ($http, UrlUtils, $ionicLoading) {

	var URL = UrlUtils.BASE_URL;

	var post = function post(_ref) {
		var name = _ref.name;
		var params = _ref.params;
		var callback = _ref.callback;

		var url = name;
		alert(url);
		var req = {
			method: 'POST',
			url: url,
			headers: {
				'Content-Type': 'undefined'
				//'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
			},
			transformRequest: angular.identity,
			data: params
		};

		$http(req).success(function (response) {
			//响应成功
			console.log("检测请求返回：");
			console.log(response);
			if (response.code == 200) {
				if (response.data != null) {
					callback.success && callback.success(response.data);
				} else {
					callback.success && callback.success(response);
				}
			} else {
				callback.failed && callback.failed(response.msg);
				if (callback.failed == null) alert(response.msg);
			}
		}).error(function (response) {
			//处理响应失败
			alert("连接服务失败！");
		});
	};

	return post;
}]).factory('HttpUploadService', ['$http', 'UrlUtils', 'UserService', function ($http, UrlUtils, UserService) {
    var upload = function upload(fileURL, callback, isUri) {

        var uri = encodeURI("http://wanchabang.52kaike.com/api/image/upload");

        var win = function win(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
            var dataArray = JSON.parse(r.response);
//            callback.success(dataArray.data[0].uri);
            if (isUri) {
                callback.success(dataArray.data[0].uri);
            } else {
                callback.success(dataArray.data[0].url);
            }

        };

        var fail = function fail(error) {
            alert("An error has occurred: Code = " + error.code);
            console.log("upload error source " + error.source);
            console.log("upload error target " + error.target);
            callback.failed();
        };

        var user = UserService.getUserAcceptCache();
        var options = new FileUploadOptions();
        options.fileKey = "imglist";
        options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);

        var params = {
            user_id: user.id,
        };

        options.params = params;

        var ft = new FileTransfer();
        ft.upload(fileURL, uri, win, fail, options);
    }

    var uploadMuitl = function uploadMuitl(fileURLs, callback, isUri) {

        var size = fileURLs.length;
        var pos = 0;
        var result = [];

        var innerCallback = {
            success: function success(url) {
                result.push(url);
                pos ++;
                if (pos < size) {
                    upload(fileURLs[pos], innerCallback);
                } else {
                    callback.success(result);
                }

            },
            fail: function failed() {
                pos ++;
                if (pos < size) {
                    upload(fileURLs[pos], innerCallback);
                } else {
                    if (result.length === 0) {
                        callback.failed();
                    } else {
                        callback.success(result);
                    }

                }
            }
        };

        upload(fileURLs[pos], innerCallback, isUri)

    }

    return {
        upload: upload,
        uploadMuitl: uploadMuitl,
    }

}]).factory('UserService', ['$window', 'HttpService', '$state', function ($window, HttpService, $state) {

	var getUserAcceptCache = function getUserAcceptCache(isNeedLogin) {

		var user = $window.localStorage['user'];
		if (user == null) {} else {
			try {
				user = JSON.parse(user);
			} catch (err) {
				user = null;
			}
		}

		if (user == null) {
			if (isNeedLogin)
				alert("需要登录后才能进行此操作~");

			if (isNeedLogin) {
				$state.go('account-login');
			}
			return {};
		} else {
			return user;
		}
	};

	var getUserMustRefresh = function getUserMustRefresh(callback) {

		var user = $window.localStorage['user'];
		if (user == null) {} else {
			try {
				user = JSON.parse(user);
			} catch (err) {
				user = null;
			}
		}

		if (user == null) {
			if (!$state.is('account-login')) $state.go('account-login');
		} else {
			callback.failed = function (err) {
				if (!$state.is('account-login')) $state.go('account-login');
			};

			HttpService({ name: 'user/show', params: { user_id: user.id, target_id: user.id }, callback: callback });
		};
	};

	var goToUserDetailPage = function goToUserDetailPage(id) {
		$state.go('other-account', { id: id });
	};

	var goToChatPage = function goToChatPage(user) {
		$state.go('chat', { id: user });
	};

	var goToGroupChatPage = function goToGroupChatPage(user) {
		$state.go('chat_group', { user: user });
	};

	return {
		getUserAcceptCache: getUserAcceptCache,
		getUserMustRefresh: getUserMustRefresh,
		goToUserDetailPage: goToUserDetailPage,
		goToChatPage: goToChatPage,
		goToGroupChatPage: goToGroupChatPage

	};
}]).factory('MsgService', ['$window', 'HttpService', '$state', function ($window, HttpService, $state) {

	var isConnected = false;

	// 初始化融云
	var initRongCloud = function initRongCloud(callback) {
		var token = $window.localStorage['token'];

		if (token != null) {

			RongCloudLibPlugin.init({
				appKey: 'mgb7ka1nbzewg' }, function (ret, err) {
				if (ret.status == 'error') {
					console.log('init error code = ' + err.code);
				}
			});

			RongCloudLibPlugin.connect({ token: token }, function (ret, err) {
				if (ret.status == 'success') console.log('connect success');
				isConnected = true;
				if (callback!= null) {
					callback.success();
				}
			});

			RongCloudLibPlugin.setConnectionStatusListener(function (ret, err) {
				if (ret) {
					console.log('setConnectionStatusListener:' + JSON.stringify(ret));
					if (ret.result.connectionStatus == 'KICKED') {
						/* alert('您的帐号已在其他端登录!');
       $rootScope.hideTabs = false;
       $ionicHistory.clearCache();
       $state.go('login');*/

						isConnected = false;
					}
				}
				if (err) {
					console.log('setConnectionStatusListener error:' + JSON.stringify(err));
				}
			});
		}
	};

	// get msgs
	var getHistoryMessage = function getHistoryMessage(targetId, oldestMessageId, callback) {
		if (!isConnected) return;
		console.log('targetId = ' + targetId);
		console.log('oldestMessageId = ' + oldestMessageId);
		RongCloudLibPlugin.getHistoryMessagesByObjectName({
			conversationType: 'PRIVATE',
			targetId: targetId,
			objectName: 'RC:TxtMsg',
			oldestMessageId: oldestMessageId,
			count: 20
		}, function (ret, err) {
			if (err || ret.status != 'success') {
				console.log(JSON.stringify(err));
				callback.failed(err);
			} else {
				console.log(JSON.stringify(ret));
				callback.success(ret.result);
			}
			// alert(JSON.stringify(ret.result));
		});
	};

	var getLastestMessages = function getLastestMessages(targetId, callback) {
		if (!isConnected) return;
		RongCloudLibPlugin.getLatestMessages({
			conversationType: "PRIVATE",
			targetId: targetId,
			count: 99
		}, function (ret, err) {
			if (ret) {

				console.log('getLastestMessages ret = ' + JSON.stringify(ret));

				if (ret.result.length <= 0) {
					console.info("getLatestMessages结果为空,无法比较!");
					return;
				} else {
					//
					console.log('load success callback = ' + callback);
					callback.success(ret.result);
				}

				// expectResult = {
				//   status: 'success',
				//   result: [{
				//     content: {
				//       text: 'Hello world!',
				//       extra: ''
				//     }, // 消息内容
				//     extra: '', // 消息的附加信息，此信息只保存在本地
				//     conversationType: 'PRIVATE', // 参见 会话类型 枚举
				//     messageDirection: 'SEND', // 消息方向：SEND 或者 RECEIVE
				//     targetId: '55', // 这里对应消息发送者的 userId
				//     objectName: 'RC:TxtMsg', // 消息类型，参见 http://docs.rongcloud.cn/android_message.html#_内置内容类消息
				//     sentStatus: 'SENDING', // 参见 发送出的消息状态
				//     senderUserId: '55', // 发送者 userId
				//     messageId: 608, // 本地消息 Id
				//     sentTime: 1418971531533, // 发送消息的时间戳，从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的毫秒数
				//     receivedTime: 0 // 收到消息的时间戳，从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的毫秒数
				//   }]
				// };
				//
				// if (jsonEqualsStruc(expectResult.result[0], ret.result[0]))
				//   console.info("getLatestMessages success!");
				// else {
				//   console.error("getLatestMessages error!");
				//   console.error("expected:" + JSON.stringify(expectResult.result[0]));
				//   console.error("actural:" + JSON.stringify(ret.result[0]));
				// }
			}
			if (err) {
				alert('getLatestMessages err:' + JSON.stringify(err));
			}
		});
	};

	var getLastestGroupMessages = function getLastestGroupMessages(targetId, callback) {
		if (!isConnected) return;
		RongCloudLibPlugin.getLatestMessages({
			conversationType: "GROUP",
			targetId: targetId,
			count: 99
		}, function (ret, err) {
			if (ret) {

				console.log('getLastestGroupMessages ret = ' + JSON.stringify(ret));

				if (ret.result.length <= 0) {
					console.info("getLastestGroupMessages结果为空,无法比较!");
					return;
				} else {
					//
					console.log('load success callback = ' + callback);
					callback.success(ret.result);
				}

				// expectResult = {
				//   status: 'success',
				//   result: [{
				//     content: {
				//       text: 'Hello world!',
				//       extra: ''
				//     }, // 消息内容
				//     extra: '', // 消息的附加信息，此信息只保存在本地
				//     conversationType: 'PRIVATE', // 参见 会话类型 枚举
				//     messageDirection: 'SEND', // 消息方向：SEND 或者 RECEIVE
				//     targetId: '55', // 这里对应消息发送者的 userId
				//     objectName: 'RC:TxtMsg', // 消息类型，参见 http://docs.rongcloud.cn/android_message.html#_内置内容类消息
				//     sentStatus: 'SENDING', // 参见 发送出的消息状态
				//     senderUserId: '55', // 发送者 userId
				//     messageId: 608, // 本地消息 Id
				//     sentTime: 1418971531533, // 发送消息的时间戳，从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的毫秒数
				//     receivedTime: 0 // 收到消息的时间戳，从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的毫秒数
				//   }]
				// };
				//
				// if (jsonEqualsStruc(expectResult.result[0], ret.result[0]))
				//   console.info("getLatestMessages success!");
				// else {
				//   console.error("getLatestMessages error!");
				//   console.error("expected:" + JSON.stringify(expectResult.result[0]));
				//   console.error("actural:" + JSON.stringify(ret.result[0]));
				// }
			}
			if (err) {
				alert('getLatestMessages err:' + JSON.stringify(err));
			}
		});
	};

	var sendMessage = function sendMessage(targetId, text) {
		if (!isConnected) return;
		// 之前调用 init 和 connect 的代码省略

		RongCloudLibPlugin.sendTextMessage({
			conversationType: 'PRIVATE',
			targetId: targetId,
			text: text.message,
			extra: JSON.stringify(text.extra)
		}, function (ret, err) {
			console.log(JSON.stringify(ret));
// 			if (ret.status == 'prepare') {
// //			    alert(JSON.stringify(ret.result.message));
// 			} else if (ret.status == 'success') {
// //			    alert(ret.result.message.messageId);
// 			} else if (ret.status == 'error') {
// 			    alert(err.code);
// 			}
		});
	};

	var sendGroupMessage = function sendGroupMessage(targetId, text) {
		if (!isConnected) return;
		RongCloudLibPlugin.sendTextMessage({
			conversationType: 'GROUP',
			targetId: targetId,
			text: text.message,
			extra: JSON.stringify(text.extra)
		}, function (ret, err) {
			if (err) {
				console.log(JSON.stringify(err));
			};

   //          if (ret.status == 'prepare') {
   // //			    alert(JSON.stringify(ret.result.message));
   //          } else if (ret.status == 'success') {
   // //			    alert(ret.result.message.messageId);
   //          } else if (ret.status == 'error') {
   //              alert(err.code);
   //          }
        });
	};

	var timeFormat = function timeFormat(time, format) {
		var t = new Date(time);
		var tf = function tf(i) {
			return (i < 10 ? '0' : '') + i;
		};
		return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
			switch (a) {
				case 'yyyy':
					return tf(t.getFullYear());
					break;
				case 'MM':
					return tf(t.getMonth() + 1);
					break;
				case 'mm':
					return tf(t.getMinutes());
					break;
				case 'dd':
					return tf(t.getDate());
					break;
				case 'HH':
					return tf(t.getHours());
					break;
				case 'ss':
					return tf(t.getSeconds());
					break;
			}
		});
	};

	var getUnreadNumber = function(callback) {
		if (!isConnected) return;
		RongCloudLibPlugin.getConversationList(function (ret, err) {

      console.log(JSON.stringify(ret.result));
      var conversationList = ret.result;

			var newMessage = 0;
			var newGroupMessage = 0;

      for (var i = 0; i < conversationList.length; i++) {

        if (conversationList[i].conversationType === 'PRIVATE') {
			newMessage += conversationList[i].unreadMessageCount;
        } else if (conversationList[i].conversationType === 'GROUP') {
        	newGroupMessage += conversationList[i].unreadMessageCount;
        }

      }

			callback.success(newMessage, newGroupMessage);

	  });
	};

	return {
		initRongCloud: initRongCloud,
		getHistoryMessage: getHistoryMessage,
		sendMessage: sendMessage,
		getLastestMessages: getLastestMessages,
		sendGroupMessage: sendGroupMessage,
		getLastestGroupMessages: getLastestGroupMessages,
		timeFormat: timeFormat,
		isConnected: isConnected,
		getUnreadNumber: getUnreadNumber,
	};
}]).factory('ShareService', function ($cordovaClipboard) {

	var shareMessage = function shareMessage(content) {
		// this is the complete list of currently supported params you can pass to the plugin (all optional)
		var options = {
			message: content, // not supported on some apps (Facebook, Instagram)
			subject: 'the subject', // fi. for email
			files: [], // an array of filenames either locally or remotely
			url: '',
			chooserTitle: '分享到' // Android only, you can override the default share sheet title
		};

		var onSuccess = function onSuccess(result) {
			console.log("Share completed? " + result.completed); // On Android apps mostly return false even while it's true
			console.log("Shared to app: " + result.app); // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)
		};

		var onError = function onError(msg) {
            alert(msg);
			console.log("Sharing failed with message: " + msg);
		};

        // copy content
        $cordovaClipboard
        .copy(content)
        .then(function () {
              // success
              window.plugins.socialsharing.shareWithOptions(options, onSuccess, onError);
              }, function () {
              // error
              });
	};

	var shareImgMsg = function shareImgMsg(content, files) {
		// this is the complete list of currently supported params you can pass to the plugin (all optional)
		var options = {
			message: '', // not supported on some apps (Facebook, Instagram)
			subject: 'the subject', // fi. for email
			files: files, // an array of filenames either locally or remotely
			url: '',
			chooserTitle: '分享到' // Android only, you can override the default share sheet title
		};

		var onSuccess = function onSuccess(result) {
			console.log("Share completed? " + result.completed); // On Android apps mostly return false even while it's true
			console.log("Shared to app: " + result.app); // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)
		};

		var onError = function onError(msg) {
            alert(msg);
			console.log("Sharing failed with message: " + msg);
		};
		// copy content
		$cordovaClipboard
		.copy(content)
		.then(function () {
					// success
					window.plugins.socialsharing.shareWithOptions(options, onSuccess, onError);
					}, function () {
					// error
					});

	};


	return {
		share: shareMessage,
		shareImgMsg: shareImgMsg,
	};
}).factory('YuBiHistory', function ($state) {

	var stack = [];

	return {
		push: function(state) {
			stack.add(state);
		},
		back: function() {

		},
	};

}).factory('ImageService', ['$ionicActionSheet', '$cordovaCamera', function($ionicActionSheet, $cordovaCamera){

	//选择相册或者拍照
	var selectImgType = function (callback) {

		// 显示操作表
		$ionicActionSheet.show({
			cssClass: "user-sheet",
			buttons: [{ text: '拍照' }, { text: '从相册选择' }],
			titleText: '选择图片',
			cancelText: '取消',
			buttonClicked: function buttonClicked(index) {
				if (index == 0) {
					takePhoto(callback);
				}
				if (index == 1) {
					from_gallery(callback);
				}
				return true;
			}
		});
	};

	//相册选择
	var from_gallery = function (callback) {

		// destinationType: Camera.DestinationType.FILE_URI,
		var options = {
      		targetWidth: 1080, //照片宽度
			targetHeight: 1920, //照片高度
			sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
		};

		$cordovaCamera.getPicture(options).then(function (imageURI) {
			console.log('imageURI = ' + imageURI);
			callback.success(imageURI);
		}, function (err) {
			// error
			console.log(err);
			alert('暂不支持该格式的图片上传!');
		});
	};

	//拍照
	var takePhoto = function (callback) {

		var options = {
			quality: 100, //相片质量0-100
			destinationType: Camera.DestinationType.FILE_URI, //返回类型：DATA_URL= 0，返回作为 base64 編碼字串。 FILE_URI=1，返回影像档的 URI。NATIVE_URI=2，返回图像本机URI (例如，資產庫)
			sourceType: Camera.PictureSourceType.CAMERA, //从哪里选择图片：PHOTOLIBRARY=0，相机拍照=1，SAVEDPHOTOALBUM=2。0和1其实都是本地图库
			allowEdit: false, //在选择之前允许修改截图
			encodingType: Camera.EncodingType.JPEG, //保存的图片格式： JPEG = 0, PNG = 1
			targetWidth: 1080, //照片宽度
			targetHeight: 1920, //照片高度
			mediaType: 0, //可选媒体类型：圖片=0，只允许选择图片將返回指定DestinationType的参数。 視頻格式=1，允许选择视频，最终返回 FILE_URI。ALLMEDIA= 2，允许所有媒体类型的选择。
			cameraDirection: 0, //枪后摄像头类型：Back= 0,Front-facing = 1
			popoverOptions: CameraPopoverOptions,
			saveToPhotoAlbum: true
		};

		$cordovaCamera.getPicture(options).then(function (imageURI) {
			console.log('imageURI = ' + imageURI);
			callback.success(imageURI);
		}, function (err) {
			console.log(err);
		});
	};

	return {
		pickImage: selectImgType,
	}

}]);
